<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写板</title>

    <style>
        .edit-panel {
            display: flex;
            justify-content: center;
        }

        .write-canvas {
            border: 1px dashed gray;
        }
    </style>
</head>
<body>
    <div class="edit-panel">
        <canvas
            id="canvas_1"
            class="write-canvas"
            width="520"
            height="158"
        >您的浏览器不支持canvas技术,请升级浏览器!</canvas>
    </div>
</body>
</html>

<script src="./write-pad-init.js"></script>
<script>

    class initPad {
        writePad = '';

        lineWidth = 'medium';

        isMoving = false;

        /** 屏幕方向 */
        direction = '';

        eraserStyle = {};

        constructor() {
            const canvas = document.querySelector('#canvas_1')

            // 触摸操控
            canvas.addEventListener('touchstart', (e) => this.writeStart(e));
            canvas.addEventListener('touchmove', (e) => this.writeTouchmove(e));
            canvas.addEventListener('touchend', (e) => this.writeEnd(e));

            // 鼠标操控
            canvas.addEventListener('mousedown', (e) => this.writeStart(e));
            canvas.addEventListener('mousemove', (e) => this.writeMousemove(e));
            canvas.addEventListener('mouseup', (e) => this.writeEnd(e));

            this.writePad = new WritePad(canvas, { backgroundIsEmpty: true });
            this.writePad.penColor = '#273039';
            this.writePad.minWidth = 0.5;
            this.writePad.maxWidth = 2;
        }

        writeStart() {
            if (this.lineWidth === 'huge') {
                this.writePad.penColor = '#fff';
            }
            this.isMoving = true;
        }

        writeMove(x, y) {
            if (this.direction === 'vertical') {
                this.eraserStyle = {
                    top: `${y - 15}px`,
                    left: `${x - 58}px`,
                };
            } else {
                this.eraserStyle = {
                    top: `${y - 58}px`,
                    left: `${x - 15}px`,
                };
            }
        }

        writeTouchmove(e) {
            let x = e.changedTouches[0].pageX,
                y = e.changedTouches[0].pageY;
            this.writeMove(x, y);
        }

        writeMousemove(e) {
            let x = e.clientX,
                y = e.clientY;

            this.writeMove(x, y);
        }

        writeEnd(e) {
            this.isMoving = false;
        }
    }

    new initPad();
</script>
